import { defineStore } from 'pinia';
import { fetchDictItems } from '@/apis/system/dict';

interface DictItem {
  label: string;
  value: string;
  raw: any;
}

interface DictCacheItem {
  data: DictItem[];
  timestamp: number;
}

// 字典缓存刷新时间，单位毫秒
const EXPIRE_TIME = 30 * 60 * 1000; // 默认 30 分钟

export const useDictStore = defineStore('dictStore', {
  state: () => ({
    dictMap: new Map<string, DictCacheItem>(),
  }),

  actions: {
    // 获取字典（带缓存）
    async getDict(type: string) {
      const cache = this.dictMap.get(type);

      // 如果有缓存，且未过期，直接返回
      if (cache && Date.now() - cache.timestamp < EXPIRE_TIME) {
        return cache.data;
      }

      // 否则请求后端
      const res = await fetchDictItems(type);
      const dictItems = (res.data || []).map((item: any) => ({
        label: item.dictLabel,
        value: item.dictValue,
        raw: item,
      })) as DictItem[];

      // 存入缓存
      this.dictMap.set(type, {
        data: dictItems,
        timestamp: Date.now(),
      });

      return dictItems;
    },

    // 强制刷新某个字典
    async refresh(type: string) {
      this.dictMap.delete(type);
      return await this.getDict(type);
    },

    // 清空所有缓存
    clearAll() {
      this.dictMap.clear();
    },
  },
});
